<script setup>
import { reactive, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { userApi } from '@/api/request'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/useUserStore'

// ===== 状态管理 =====
const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const redirectUrl = ref(null)

// 表单相关状态
const loginForm = reactive({
  username: '',
  password: '',
  role: ''
})
const loginFormRef = ref(null)
const loading = ref(false)

// ===== 表单验证规则 =====
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在3到20个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6到20个字符之间', trigger: 'blur' }
  ],
  role: [{ required: true, message: '请选择身份', trigger: 'change' }]
}

// 登录处理
const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    await loginFormRef.value.validate()
    loading.value = true

    const response = await userApi.login(loginForm)
    console.log('登录响应', response)
    if (response.data.code === 200) {
      try {
        // 获取后端返回的 token
        const token = response.data.data
        if (!token) {
          throw new Error('登录返回的 token 为空')
        }

        // 先清除所有已存在的token和角色信息
        localStorage.removeItem('user-token')
        localStorage.removeItem('admin-token')
        localStorage.removeItem('admin-role')
        sessionStorage.removeItem('user-token')
        sessionStorage.removeItem('admin-token')
        sessionStorage.removeItem('admin-role')

        // 根据角色存储 token
        if (loginForm.role === 'admin') {
          // 管理员登录：存储 admin-token
          localStorage.setItem('admin-token', token)
          sessionStorage.setItem('admin-token', token)
          // 存储角色信息
          localStorage.setItem('admin-role', 'admin')
          sessionStorage.setItem('admin-role', 'admin')
          // 存储用户名
          localStorage.setItem('username', loginForm.username)
          // 更新store状态
          userStore.setToken(token)
          userStore.setRole('admin')
          userStore.setLoggedIn(true)
          // 设置用户名
          userStore.name = loginForm.username

          ElMessage.success('管理员登录成功')
          // 确保路由实例可用
          if (router) {
            await router.push('/admin/users')
          }
        } else {
          // 普通用户登录：存储 user-token
          localStorage.setItem('user-token', token)
          sessionStorage.setItem('user-token', token)
          // 存储用户名
          localStorage.setItem('username', loginForm.username)
          // 更新store状态
          userStore.setToken(token)
          userStore.setRole('user')
          userStore.setLoggedIn(true)
          // 设置用户名
          userStore.name = loginForm.username

          ElMessage.success('用户登录成功')
          const redirect = route.query.redirect || '/home'
          await router.push(redirect)
        }
      } catch (error) {
        console.error('登录处理失败:', error)
        // 清除所有token和角色信息
        localStorage.removeItem('user-token')
        localStorage.removeItem('admin-token')
        localStorage.removeItem('admin-role')
        sessionStorage.removeItem('user-token')
        sessionStorage.removeItem('admin-token')
        sessionStorage.removeItem('admin-role')
        // 重置store状态
        userStore.resetState()
        ElMessage.error(error.message || '登录失败，请稍后重试')
      }
    } else {
      ElMessage.error(response.data.message || '登录失败')
    }
  } catch (error) {
    if (error.message) return // 表单验证错误
    console.error('登录失败:', error)
    ElMessage.error('登录失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 跳转到注册页面
const goToRegister = () => {
  router.push('/register')
}

// ===== 生命周期钩子 =====
onMounted(() => {
  redirectUrl.value = route.query.redirect
})
</script>

<template>
  <div class="login-container">
    <div class="login-box">
      <h2 class="login-title">系统登录</h2>
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="rules"
        label-width="auto"
        label-position="top"
        size="large"
        class="login-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="User"
          />
        </el-form-item>

        <el-form-item label="密码" prop="passward">
          <el-input
            v-model="loginForm.passward"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>

        <el-form-item prop="role">
          <el-radio-group v-model="loginForm.role" class="role-select">
            <el-radio label="user">用户</el-radio>
            <el-radio label="admin">管理员</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            class="submit-btn"
            @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>

        <el-form-item>
          <el-button
            type="info"
            @click="goToRegister"
            class="register-btn"
            text
          >
            还没有账号？立即注册
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-box {
  width: 400px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
  }
}

.login-title {
  text-align: center;
  color: #333;
  font-size: 24px;
  margin-bottom: 30px;
  font-weight: 600;
}

.login-form {
  .role-select {
    width: 100%;
    display: flex;
    justify-content: center;
    margin-bottom: 20px;
  }

  .submit-btn {
    width: 100%;
    height: 44px;
    font-size: 16px;
    margin-top: 20px;
    border-radius: 8px;
  }

  .register-btn {
    width: 100%;
    margin-top: 10px;
    color: #666;

    &:hover {
      color: #409eff;
    }
  }
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #333;
}
</style>
